package com.xuzz.xrpc.spring.context.xml.schema;

import com.xuzz.xrpc.spring.context.ServiceBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;

/**
 * @description:
 * @author: xuzz
 * @create: 2020-02-21 17:38
 */
public class ServiceElementParser implements BeanDefinitionParser {
    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        RootBeanDefinition beanDefinition = new RootBeanDefinition();
        //beanClass是一个FactoryBean的实现，那么在getObject的时候，会通过它
        beanDefinition.setBeanClass(ServiceBean.class);
        beanDefinition.setLazyInit(false);

        String id = element.getAttribute("id");
        if (StringUtils.isEmpty(id)) {
            String generatedBeanName = element.getAttribute("interface");
            id = generatedBeanName;
        }

        String inte = element.getAttribute("interface");
        beanDefinition.getPropertyValues().addPropertyValue("interfaceName",inte);
        String className = element.getAttribute("class");
        beanDefinition.getPropertyValues().addPropertyValue("className",className);
        if (!StringUtils.isEmpty(id)) {
            if (parserContext.getRegistry().containsBeanDefinition(id)) {
                throw new IllegalStateException("Duplicate spring bean id " + id);
            }
            parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
        }

        return beanDefinition;
    }
}
